import themeChangeBehavior from 'tdesign-miniprogram/mixins/theme-change';
const { getProductDetail } = require('../../utils/inventory-api.js');

Page({
  behaviors: [themeChangeBehavior],
  
  data: {
    productInfo: null, // 产品基本信息
    productDetail: {
      list: [],
      total: 0,
      pageNum: 1,
      pageSize: 10
    },
    loading: false,
    refreshing: false,
    hasMore: true
  },

  onLoad(options) {
    // 从页面参数获取产品信息
    if (options.productInfo) {
      try {
        const productInfo = JSON.parse(decodeURIComponent(options.productInfo));
        
        // 格式化创建时间和更新时间
        if (productInfo.createTime) {
          productInfo.createTimeFormatted = this.formatDateTime(productInfo.createTime);
        }
        if (productInfo.updateTime) {
          productInfo.updateTimeFormatted = this.formatDateTime(productInfo.updateTime);
        }
        
        this.setData({ productInfo });
        this.loadProductDetail();
      } catch (error) {
  
        wx.showToast({
          title: '参数错误',
          icon: 'none'
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      }
    } else {
      wx.showToast({
        title: '缺少产品信息',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  onShow() {
    // 页面显示时可以刷新数据
  },

  onPullDownRefresh() {
    this.refreshProductDetail();
    wx.stopPullDownRefresh();
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMoreRecords();
    }
  },

  // 加载产品详情（变化记录）
  async loadProductDetail(refresh = false) {
    const { productInfo } = this.data;
    if (!productInfo) return;

    if (refresh) {
      this.setData({ 
        refreshing: true,
        productDetail: {
          list: [],
          total: 0,
          pageNum: 1,
          pageSize: 10
        }
      });
    } else if (this.data.loading) {
      return;
    }

    this.setData({ loading: true });
    
    try {
      const params = {
        productCode: productInfo.productCode,
        color: productInfo.color,
        orderBy: 'desc',
        page: refresh ? 1 : this.data.productDetail.pageNum,
        pageSize: this.data.productDetail.pageSize
      };

      const result = await getProductDetail(params);
      
      if (result.message == "操作成功" && result.data) {
        const { list = [], total = 0, pageNum = 1, pageSize = 10, hasNextPage = false } = result.data;
        
        // 处理变化记录数据
        const processedList = list.map(item => ({
          ...item,
          changeTypeText: item.changeType === 1 ? '入库操作' : '出库操作',
          changeTypeIcon: item.changeType === 1 ? 'add-circle' : 'remove-circle',
          changeTypeColor: item.changeType === 1 ? '#52c41a' : '#fa8c16',
          createTimeFormatted: this.formatDateTime(item.createTime),
          changeQuantityWithSign: item.changeType === 1 ? `+${item.changeQuantity}` : `-${item.changeQuantity}`
        }));


        if (refresh || pageNum === 1) {
          // 刷新或首次加载
          this.setData({
            productDetail: {
              list: processedList,
              total,
              pageNum,
              pageSize
            },
            hasMore: hasNextPage
          });
        } else {
          // 加载更多
          this.setData({
            productDetail: {
              ...this.data.productDetail,
              list: [...this.data.productDetail.list, ...processedList],
              pageNum,
              total
            },
            hasMore: hasNextPage
          });
        }

      } else {
        this.setData({
          productDetail: {
            list: [],
            total: 0,
            pageNum: 1,
            pageSize: 10
          },
          hasMore: false
        });
        
        wx.showToast({
          title: result.message || '加载详情失败',
          icon: 'none'
        });
      }
    } catch (error) {

      
      this.setData({
        productDetail: {
          list: [],
          total: 0,
          pageNum: 1,
          pageSize: 10
        },
        hasMore: false
      });
      
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      });
    } finally {
      this.setData({ 
        loading: false,
        refreshing: false 
      });
    }
  },

  // 刷新产品详情
  refreshProductDetail() {
    this.loadProductDetail(true);
  },

  // 加载更多记录
  loadMoreRecords() {
    if (this.data.hasMore && !this.data.loading) {
      this.setData({
        'productDetail.pageNum': this.data.productDetail.pageNum + 1
      });
      this.loadProductDetail();
    }
  },

  // 格式化日期时间
  formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return '';
    
    try {
      const date = new Date(dateTimeStr);
      
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        return dateTimeStr; // 如果无法解析，返回原字符串
      }
      
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    } catch (error) {

      return dateTimeStr; // 发生错误时返回原字符串
    }
  },

  // 获取库存状态文本
  getStatusText(status) {
    const statusMap = {
      'normal': '正常',
      'low': '库存不足',
      'out': '缺货'
    };
    return statusMap[status] || '未知';
  },

  // 返回上一页
  onGoBack() {
    wx.navigateTo({
      url: 'pages/inventory-management/inventory-management',
    })
  }
});